// 源插件
import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import router from 'umi/router';
import { NumberDivide, DateDiff, FormatnumberZero, Mover } from '@/function.js';

// 视图插件
import {
  BackTop,
  Empty,
  Spin,
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Steps,
  Radio,
  Upload,
  notification,
} from 'antd';

// 外部组件
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import EditableItem from '@/components/EditableItem';
import Loading from '@/components/Loading/Loading';
import OptionsTableDetail from './OptionsTableDetail';

// css OR less预编译器
import styles from './PositionRuiOptionsTable.less';

// 图片

// 算式

/* 切割日期 */
function StringSplit(date) {
  // 日期
  if (typeof date === 'string') {
    return date.split(' ')[0];
  }
  return null;
}

/* 财报日剩余对比 */
function DateDiffResults(sDate2) {
  // sDate1和sDate2是yyyy-MM-dd格式
  if (typeof sDate2 === 'string') {
    let aDate;
    let oDate1;
    let oDate2;
    let iDays;
    oDate1 = new Date(); // 转换为yyyy-MM-dd格式
    aDate = sDate2.split('/');
    oDate2 = new Date(`${aDate[1]}-${aDate[2]}-${aDate[0]}`);
    iDays = parseInt(Math.abs(oDate1 - oDate2) / 900 / 60 / 60 / 24); // 把相差的毫秒数转换为天数
    return iDays; // 返回相差天数
  }
  return '暂无数据';
}
function DateStamp(param) {
  // sDate1和sDate2是yyyy-MM-dd格式
  if (typeof param === 'string') {
    const str = param.replace(/-/g, '/');
    const date = new Date(str);
    date.setDate(date.getDate() + 1);
    return date;
  }
  return false;
}

/**
 *  Created by xjc on 2019/5/15
 *  Describe:数据连接
 */

@connect(({ positionrui, loading }) => ({
  positionrui,
  loading: loading.models.positionruiRule,
}))
@Form.create()
class PositionRuiStocksOut extends PureComponent {
  componentWillMount() {}

  /**
   *  Created by xjc on 2019/5/15
   *  Describe:当前状态
   */

  state = {
    listLoading: false, // 加载状态
    selectedRows: [], // 选择行
    formValues: {
      num: 10,
      page: 1,
    }, // 表格参数
    OptionDetailVisible: false, // modal开关
    record: {}, // 当前行内容
    searchText: '', // 搜索内容
    columns: [], // 表头处理结果
  };

  /**
   *  Describe:本地搜索
   *  Created by xjc on 2019/6/4
   */

  getColumnSearchProps = dataIndex => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
      <div style={{ padding: 8 }}>
        <Input
          ref={node => {
            this.searchInput = node;
          }}
          placeholder={`Search ${dataIndex}`}
          value={selectedKeys[0]}
          onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => this.handleSearch(selectedKeys, confirm)}
          style={{ width: 188, marginBottom: 8, display: 'block' }}
        />
        <Button
          type="primary"
          onClick={() => this.handleSearch(selectedKeys, confirm)}
          icon="search"
          size="small"
          style={{ width: 90, marginRight: 8 }}
        >
          搜索
        </Button>
        <Button onClick={() => this.handleReset(clearFilters)} size="small" style={{ width: 90 }}>
          重置
        </Button>
      </div>
    ),
    filterIcon: filtered => (
      <Icon type="search" style={{ color: filtered ? '#1890ff' : '#181816', fontWeight: '700' }} />
    ),
    onFilter: (value, record) => {
      return record[dataIndex] === null
        ? ''
        : record[dataIndex]
            .toString()
            .toLowerCase()
            .includes(value.toLowerCase());
    },
    onFilterDropdownVisibleChange: visible => {
      if (visible) {
        setTimeout(() => this.searchInput.select());
      }
    },
    render: text => <span>{text}</span>,
  });

  handleSearch = (selectedKeys, confirm) => {
    confirm();
    this.setState({ searchText: selectedKeys[0] });
  };

  handleReset = clearFilters => {
    clearFilters();
    this.setState({ searchText: '' });
  };

  updateSourceperson(row, value) {
    const { dispatch } = this.props;
    dispatch({
      type: 'positionrui/AddPositionSource',
      payload: {
        sourceperson: value,
        stock: row.stock,
      },
      callback: () => {
        dispatch({
          type: 'positionrui/GetLastDayOption',
          payload: {},
        });
      },
    });
  }

  /**
   *  Created by xjc on 2019/6/14
   *  Describe:读取筛选de表头
   */
  getColumns() {
    const {
      positionrui: { stocksellFilters },
    } = this.props;
    const buydate = stocksellFilters.buydate.map(i => {
      return { text: i.split(' ')[0], value: i };
    });
    const selldate = stocksellFilters.selldate.map(i => {
      return { text: i.split(' ')[0], value: i };
    });
    const type = stocksellFilters.type.map(i => {
      if (i === 1) {
        return { text: 'SP', value: i.toString() };
      }
      if (i === 2) {
        return { text: 'SC', value: i.toString() };
      }
      if (i === 3) {
        return { text: 'BP', value: i.toString() };
      }
      if (i === 4) {
        return { text: 'BC', value: i.toString() };
      }
    });
    this.setState({
      columns: [
        {
          title: 'ID',
          width: 60,
          sorter: (a, b) => a.id - b.id,
          dataIndex: 'id',
        },
        {
          title: '股票代码',
          width: 110,
          dataIndex: 'stock',
          sorter: (a, b) => {
            const c = [a.stock, b.stock].sort();
            if (c[0] === a.stock) {
              return 1;
            }
            return -1;
          },
          ...this.getColumnSearchProps('stock'),
        },
        {
          title: '类型',
          width: 80,
          dataIndex: 'type',
          filters: type,
          onFilter: (value, record) => {
            return record.type === null ? false : record.type.toString().includes(value);
          },
          render: (value, row, index) => {
            if (value === 1) {
              return '做多';
            }
            if (value === 2) {
              return '做空';
            }
          },
        },
        {
          title: '成本价',
          width: 110,
          sorter: (a, b) => a.costprice - b.costprice,
          dataIndex: 'costprice',
          render: (value, row, index) => {
            return (
              <span>
                {typeof value === 'number' || typeof value === 'string'
                  ? NumberDivide(value.toString())
                  : null}
              </span>
            );
          },
        },
        {
          title: '新价格',
          width: 110,
          sorter: (a, b) => a.sellprice - b.sellprice,
          dataIndex: 'sellprice',
          render: (value, row, index) => {
            return (
              <span>
                {
                  <EditableItem
                    value={value}
                    aftervalue={row.exercised === 1 ? '(已行权)' : ''}
                    row={row}
                    numberIF
                    onChange={this.changeNewPrice.bind(this)}
                  />
                }
              </span>
            );
          },
        },
        {
          title: '股数',
          width: 90,
          sorter: (a, b) => a.stocknumber - b.stocknumber,
          dataIndex: 'stocknumber',
          render: (value, row, index) => {
            return (
              <span>
                {typeof value === 'number' || typeof value === 'string'
                  ? NumberDivide(value.toString())
                  : null}
              </span>
            );
          },
        },
        {
          title: '收益',
          width: 110,
          sorter: (a, b) => a.income - b.income,
          dataIndex: 'income',
          render: (value, row, index) => {
            return (
              <span>
                {typeof value === 'number' || typeof value === 'string'
                  ? NumberDivide(value.toString())
                  : null}
              </span>
            );
          },
        },
        {
          title: '购买时间',
          width: 110,
          dataIndex: 'buydate',
          filters: buydate,
          onFilter: (value, record) => {
            return record.buydate === null ? false : record.buydate.toString().includes(value);
          },
          render: (value, row, index) => {
            return <span>{typeof value === 'string' ? value.split(' ')[0] : ''}</span>;
          },
        },
        {
          title: '卖出时间',
          width: 110,
          dataIndex: 'selldate',
          filters: selldate,
          onFilter: (value, record) => {
            return record.selldate === null ? false : record.selldate.toString().includes(value);
          },
          render: (value, row, index) => {
            return <span>{typeof value === 'string' ? value.split(' ')[0] : ''}</span>;
          },
        },
        {
          title: '操作',
          width: 70,
          render: (value, row, index) => {
            return (
              <Fragment>
                {row.type === 2 || row.type === 1 ? (
                  <a onClick={() => this.outOption(value, row)}>行权</a>
                ) : null}
              </Fragment>
            );
          },
        },
      ],
    });
  }

  changeNewPrice(value, row) {
    const { dispatch } = this.props;
    if (value < 0) {
      notification.error({
        message: '数据不可小于0',
      });
      dispatch({
        type: 'positionrui/GetUBSSellStock',
        payload: {},
      });
      return false;
    }

    dispatch({
      type: 'positionrui/UpdateStockSellPrice',
      payload: {
        sellPrice: value,
        exercised: false,
        id: row.id,
      },
      callback: () => {
        /* 导入列表数据 */
        dispatch({
          type: 'positionrui/GetUBSSellStock',
          payload: {},
        });
      },
    });
    return true;
  }

  outOption(value, row) {
    const { dispatch } = this.props;
    dispatch({
      type: 'positionrui/UpdateStockSellPrice',
      payload: {
        sellPrice: 0,
        exercised: true,
        id: row.id,
      },
      callback: () => {
        /* 导入列表数据 */
        dispatch({
          type: 'positionrui/GetUBSSellStock',
          payload: {},
        });
      },
    });
  }

  /**
   *  Created by xjc on 2019/5/15
   *  Describe:视图
   */

  render() {
    const {
      loading,
      positionrui: { stocksell, stocksellFilters },
    } = this.props;
    const { listLoading, selectedRows, record, OptionDetailVisible, columns } = this.state;
    if (columns.length === 0 && stocksell.list.length !== 0) {
      this.getColumns();
    }
    return (
      <PageHeaderWrapper title="瑞银股票卖出管理">
        <Card>
          {stocksell.list.length === 0 ? (
            <Loading />
          ) : (
            <StandardTable
              selectedRows={selectedRows}
              loading={listLoading}
              data={stocksell}
              pagination={false}
              columns={columns}
              style={{ tableLayout: 'fixed' }}
              className={styles.TableLayout}
              rowKey="id"
              scroll={{ x: 1400, y: 618 }}
            />
          )}
        </Card>
      </PageHeaderWrapper>
    );
  }

  componentDidMount() {
    const { dispatch } = this.props;

    /* 导入列表数据 */
    dispatch({
      type: 'positionrui/GetUBSSellStock',
      payload: {},
    });
  }

  componentWillUnmount() {}
}

export default PositionRuiStocksOut;
